package autoupdate.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static autoupdate.test.AutoUpdateConstants.*;

public class VersionFileReader{
	public static List<Module> getModuleUpdateList(){

		
		
		Map<String, Module> currentModules;
		Map<String, Module> newestModules;
		List<Module> staleModules = new ArrayList<Module>();
		try{
			InputStream stream = new FileInputStream(CURRENT_VERSIONS_FILE);
			currentModules = readModuleVersionFile(stream);
			stream.close();
			
			URL url = new URL(TEST_VERSIONS_FILE);
			stream = url.openStream();
			newestModules = readModuleVersionFile(stream);
			stream.close();
			
			Iterator<String> i2 = currentModules.keySet().iterator();
			while (i2.hasNext()) {
				String moduleName = i2.next();
				/*
		        System.out.println(moduleName);
		        System.out.println(currentModules.get(moduleName));
		        System.out.println(newestModules.containsKey(moduleName));
		        */
				if(newestModules.containsKey(moduleName)){
					//if < 0, need update
					if(currentModules.get(moduleName).compareTo(newestModules.get(moduleName)) < 0){
						staleModules.add(newestModules.get(moduleName));
					}
				}
		    }

		}catch(FileNotFoundException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return staleModules;
	}
	
	private static Map<String, Module> readModuleVersionFile(InputStream inputStream){
		Map<String, Module> moduleMap = new HashMap<String, Module>();
		
		try{
			Properties properties = new Properties();
			properties.load(inputStream);
	
			Collection<Object> collection = properties.values();
			Iterator<Object> i = collection.iterator();
			String version;
			String[] splitString;
			while(i.hasNext()){
				version = (String)i.next();
				splitString = version.split("[,]");
				if(splitString.length == 2)
					moduleMap.put(splitString[1].trim(), new Module("moduleName", new VersionNumber(splitString[0].trim()), splitString[1].trim()));
				else if(splitString.length == 3)
					moduleMap.put(splitString[1].trim(), new Module("moduleName", new VersionNumber(splitString[0].trim()), splitString[1].trim(), splitString[2].trim()));
				else
					throw new Exception("invalid version split: " + splitString.length);
			}
		}catch(IOException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return moduleMap;
	}
}
